package cn.xdwanj.ask.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.xdwanj.ask.entity.Askclass;
import cn.xdwanj.ask.entity.Asklist;
import cn.xdwanj.ask.entity.PostData;
import cn.xdwanj.ask.service.AskclassService;
import cn.xdwanj.ask.service.AsklistService;
import cn.xdwanj.ask.service.UserService;
import com.alibaba.fastjson.JSON;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author xdwanj
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/post")
public class PostController {

    private final AsklistService asklistService;
    private final AskclassService askclassService;
    private final UserService userService;

    public boolean isLogin(
        @Parameter(hidden = true)
        @SessionAttribute("islogin")
        Object isLogin
    ) {
        return isLogin != null;
    }

    @RequestMapping("/newpost.do")
    public Map<String, String> newpost(@RequestParam("json") String json,
                                       @Parameter(hidden = true)
                                       @SessionAttribute("userid") int userid
    ) {

        PostData postData = JSON.parseObject(json, PostData.class);

        var asklist = new Asklist();
        asklist.setTitle(postData.getTitle());
        asklist.setContent(postData.getContent());
        asklist.setClazz(postData.getClassid());
        asklist.setUserid(userid);
        asklist.setCreattime(LocalDateTime.now());
        var isSaveSuccess = asklistService.save(asklist);

        if (!isSaveSuccess) {
            return Map.of(
                "msg", "未知错误",
                "code", "1"
            );
        }

        return Map.of(
            "msg", "发布成功",
            "code", "0"
        );

    }

    @RequestMapping("/gettotalask.do")
    public long getTotalAsk() {
        return asklistService.count();
    }

    @RequestMapping("/getaskclass.do")
    public List<Askclass> getAskClassJson() {
        return askclassService.list();
    }

    @RequestMapping("/getAsk.do")
    public Map<String, Object> getAsk(int id,
                                      @Parameter(hidden = true)
                                      @SessionAttribute("userid") int userid) {
        var asklist = asklistService.getById(id);
        var view = Optional.ofNullable(asklist.getView())
            .orElse(0);
        asklistService.lambdaUpdate()
            .eq(Asklist::getId, id)
            .set(Asklist::getView, view + 1)
            .update();

        log.info("{}", asklist);
        var askclass = askclassService.lambdaQuery()
            .eq(Askclass::getId, asklist.getClazz())
            .one();
        var userInfo = userService.getById(asklist.getUserid());

        var ask = BeanUtil.beanToMap(asklist);

        ask.put("classname", Optional.ofNullable(askclass)
            .map(Askclass::getName)
            .orElse("")
        );
        ask.put("classcolor", Optional.ofNullable(askclass)
            .map(Askclass::getColor)
            .orElse("")
        );
        ask.put("username", userInfo.getName());

        if (userid == asklist.getUserid()) {
            ask.put("own", 1);
        } else {
            ask.put("own", 0);
        }

        return ask;

    }

    @RequestMapping("/search.do")
    public List<Map<String, Object>> search(String key) {
        var asklistList = asklistService.lambdaQuery()
            // .select(Asklist::getId)
            // .select(Asklist::getTitle)
            // .select(Asklist::getClazz)
            .like(Asklist::getContent, key)
            .or()
            .like(Asklist::getTitle, key)
            .list();

        return asklistList.stream()
            .map(it -> BeanUtil.beanToMap(it, false, true))
            .peek(it -> {
                // it.put("class", it.get("clazz"));
                // it.remove("clazz");
                var askclass = askclassService.getById((Integer) it.get("class"));
                if (askclass == null) {
                    return;
                }
                it.put("classname", askclass.getName());
                it.put("classccolor", askclass.getColor());
            }).collect(Collectors.toList());
    }

    @RequestMapping("delask.do")
    public Map<String, Object> delask(int id) {

        var isRemoveSuccess = asklistService.removeById(id);

        return isRemoveSuccess
            ? Map.of("code", "1", "msg", "删除成功")
            : Map.of("code", "0", "msg", "删除失败");
    }

}
